import axios from 'axios'
import React, { useEffect, useState } from 'react'
import { Search as VantSearch, Space } from 'react-vant'
import { ListItemRawState } from '../../types'
import { ListItem } from '../../components'
import { useNavigate } from 'react-router-dom'
import { debounce  } from 'lodash'
const Search: React.FC = () => {
  const [list, setList] = useState<ListItemRawState[]>([])
  const navigate = useNavigate()
  const search = debounce((value: string) => {
    if(value === '') return ;
    fetchList(value);
    const data = [...new Set([value ,...searchList])]
    setSearchList(data)
  }, 800)
  const fetchList = async (value: string) => {
    const resp = await axios.get('/api/search', { params: { value } });
    setList(resp.data.data)
  }
  const [searchList, setSearchList] = useState<string[]>(JSON.parse(localStorage.getItem('searchList') || '[]'));
  useEffect(() => {
    localStorage.setItem('searchList', JSON.stringify(searchList))
  }, [searchList])
  return (
    <div>
      <VantSearch onChange={(value) => search(value)}></VantSearch>
      <div>
        <h2>
          <span>历史记录</span>
          <span>删除</span>
        </h2>
        <Space>
          {
            searchList.map((v, i) => {
              return <span key={i}>{v}</span>
            })
          }
        </Space>
      </div>
      <div>
        {
          list.map((v, i) => {
            return <ListItem key={i} v={v} desc={v.desc} onClick={() => navigate('/detail/' + v.id)}></ListItem>
          })
        }
      </div>
    </div>
  )
}


export default Search